<template>
  <div class="workorder-dashboard">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>工单仪表盘</h2>
      <el-button type="primary" @click="handleRefresh">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <!-- 概览卡片 - 工单总数统计 -->
    <div class="overview-cards">
      <el-card class="card">
        <div class="stat-item">
          <div class="stat-icon" style="background: #409eff">
            <el-icon><Document /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">总工单数</div>
            <div class="stat-value">{{ overview.total }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="card">
        <div class="stat-item">
          <div class="stat-icon" style="background: #e6a23c">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">进行中</div>
            <div class="stat-value">{{ overview.in_progress }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="card">
        <div class="stat-item">
          <div class="stat-icon" style="background: #67c23a">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">已完成</div>
            <div class="stat-value">{{ overview.completed }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="card">
        <div class="stat-item">
          <div class="stat-icon" style="background: #f56c6c">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">待分配</div>
            <div class="stat-value">{{ overview.pending }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 - 工单分布 -->
    <div class="charts-row">
      <el-card class="chart-card">
        <template #header>
          <span>工单状态分布</span>
        </template>
        <div ref="statusChartRef" class="chart"></div>
      </el-card>

      <el-card class="chart-card">
        <template #header>
          <span>工单类别分布</span>
        </template>
        <div ref="categoryChartRef" class="chart"></div>
      </el-card>
    </div>

    <!-- 最近工单 - 仪表盘特色 -->
    <el-card class="table-card">
      <template #header>
        <span>最近工单</span>
      </template>
      <el-table :data="recentWorkOrders" stripe>
        <el-table-column prop="work_order_no" label="工单编号" width="150" />
        <el-table-column prop="title" label="工单标题" min-width="200" />
        <el-table-column prop="customer_name" label="客户" width="150" />
        <el-table-column prop="category" label="类别" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.category === 1" type="danger">案件委托</el-tag>
            <el-tag v-else type="primary">法务</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="info">待分配</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="warning">进行中</el-tag>
            <el-tag v-else-if="scope.row.status === 3" type="success">已完成</el-tag>
            <el-tag v-else type="danger">已取消</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.create_time) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, onUnmounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Document, Clock, Check, Warning, Refresh } from '@element-plus/icons-vue'

  // 概览数据
  const overview = reactive({
    total: 0,
    in_progress: 0,
    completed: 0,
    pending: 0,
    cancelled: 0,
  })

  // 最近工单
  const recentWorkOrders = ref([])

  // 图表引用
  const statusChartRef = ref()
  const categoryChartRef = ref()

  // 工单类别分布数据
  const categoryDistribution = reactive({
    case_delegation: 0,
    legal_order: 0,
  })

  // 获取工单类别分布数据
  const fetchCategoryDistribution = async () => {
    try {
      const request = (await import('@/utils/request')).default
      // 由于后端没有直接提供类别分布的接口，我们通过获取工单列表来统计
      const res = (await request({
        url: '/api/workorder/workOrder/list',
        method: 'get',
        params: { limit: 1000 }, // 获取足够多的数据进行统计
      })) as any
      if (res.code === 0 && res.data?.list) {
        const list = res.data.list
        let caseCount = 0
        let legalCount = 0

        list.forEach((item: any) => {
          if (item.category === 1) {
            caseCount++
          } else if (item.category === 2) {
            legalCount++
          }
        })

        categoryDistribution.case_delegation = caseCount
        categoryDistribution.legal_order = legalCount
      }
    } catch (error) {
      console.error('获取工单类别分布数据失败:', error)
    }
  }

  // 初始化
  onMounted(() => {
    fetchOverviewData()
    fetchRecentWorkOrders()
    fetchCategoryDistribution()
    initCharts()
  })

  // 获取概览数据
  const fetchOverviewData = async () => {
    try {
      const request = (await import('@/utils/request')).default
      const res = (await request({
        url: '/api/workorder/workOrder/assignmentStats',
        method: 'get',
      })) as any
      if (res.code === 0) {
        Object.assign(overview, {
          total: res.data.total_assignments || 0,
          in_progress: res.data.in_progress || 0,
          completed: res.data.completed || 0,
          pending: res.data.pending || 0,
          cancelled: res.data.cancelled || 0,
        })
      }
    } catch (error) {
      console.error('获取概览数据失败:', error)
      ElMessage.error('获取概览数据失败')
    }
  }

  // 获取最近工单
  const fetchRecentWorkOrders = async () => {
    try {
      const request = (await import('@/utils/request')).default
      const res = (await request({
        url: '/api/workorder/workOrder/list',
        method: 'get',
        params: { limit: 10, status: 'all' },
      })) as any
      if (res.code === 0) {
        recentWorkOrders.value = res.data?.list || []
      }
    } catch (error) {
      console.error(error)
    }
  }

  // 存储图表实例
  const chartInstances = ref<any[]>([])

  // 初始化图表
  const initCharts = async () => {
    try {
      let echarts
      try {
        echarts = await import('echarts')
      } catch (importError) {
        console.error('ECharts 模块导入失败:', importError)
        ElMessage.error('图表组件加载失败')
        return
      }

      if (!echarts || typeof echarts.init !== 'function') {
        console.error('ECharts 库导入失败或不完整，缺少 init 方法')
        ElMessage.error('图表组件初始化失败')
        return
      }

      // 清理已存在的图表实例
      chartInstances.value.forEach(instance => {
        if (instance && typeof instance.dispose === 'function') {
          instance.dispose()
        }
      })
      chartInstances.value = []

      // 初始化状态分布图表
      if (statusChartRef.value && typeof statusChartRef.value === 'object') {
        try {
          const chart = echarts.init(statusChartRef.value)
          chartInstances.value.push(chart)

          chart.setOption({
            title: { text: '工单状态分布', left: 'center' },
            tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
            legend: {
              orient: 'vertical',
              left: 'left',
              data: ['待分配', '进行中', '已完成', '已取消'],
            },
            series: [
              {
                name: '工单状态',
                type: 'pie',
                radius: '50%',
                data: [
                  { value: overview.pending || 0, name: '待分配' },
                  { value: overview.in_progress || 0, name: '进行中' },
                  { value: overview.completed || 0, name: '已完成' },
                  { value: overview.cancelled || 0, name: '已取消' },
                ],
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)',
                  },
                },
              },
            ],
          })

          const resizeHandler = () => chart.resize()
          window.addEventListener('resize', resizeHandler)
          // 保存resizeHandler引用以便在组件卸载时清理
          chartInstances.value.push({ instance: chart, resizeHandler })
        } catch (chartError) {
          console.error('状态分布图初始化失败:', chartError)
        }
      }

      // 初始化类别分布图表
      if (categoryChartRef.value && typeof categoryChartRef.value === 'object') {
        try {
          const chart = echarts.init(categoryChartRef.value)
          chart.setOption({
            title: { text: '工单类别分布', left: 'center' },
            tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
            legend: { orient: 'vertical', left: 'left', data: ['案件委托', '法务订单'] },
            series: [
              {
                name: '工单类别',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
                label: { show: false, position: 'center' },
                emphasis: { label: { show: true, fontSize: 20, fontWeight: 'bold' } },
                labelLine: { show: false },
                data: [
                  { value: categoryDistribution.case_delegation || 0, name: '案件委托' },
                  { value: categoryDistribution.legal_order || 0, name: '法务订单' },
                ],
              },
            ],
          })

          const resizeHandler = () => chart.resize()
          window.addEventListener('resize', resizeHandler)
          // 保存resizeHandler引用以便在组件卸载时清理
          chartInstances.value.push({ instance: chart, resizeHandler })
        } catch (chartError) {
          console.error('类别分布图初始化失败:', chartError)
        }
      }
    } catch (error) {
      console.error('ECharts 初始化失败:', error)
    }
  }

  // 组件卸载时清理图表实例和事件监听器
  onUnmounted(() => {
    chartInstances.value.forEach(item => {
      // 移除resize事件监听器
      if (item.resizeHandler) {
        window.removeEventListener('resize', item.resizeHandler)
      }
      // 销毁图表实例
      if (item.instance && typeof item.instance.dispose === 'function') {
        item.instance.dispose()
      }
    })
    // 清空图表实例数组
    chartInstances.value = []
  })

  // 刷新数据
  const handleRefresh = () => {
    fetchOverviewData()
    fetchRecentWorkOrders()
    fetchCategoryDistribution()
    // 等待数据更新后再重新初始化图表
    setTimeout(() => {
      initCharts()
    }, 100)
  }

  // 格式化日期
  const formatDateTime = (timestamp: number | string) => {
    if (!timestamp) return ''
    const date = new Date(
      typeof timestamp === 'string' ? parseInt(timestamp) * 1000 : timestamp * 1000
    )
    return date.toLocaleString()
  }
</script>

<style lang="scss" scoped>
  .workorder-dashboard {
    padding: 20px;

    .page-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 500;
      }
    }

    .overview-cards {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 20px;
      margin-bottom: 20px;

      .card {
        .stat-item {
          display: flex;
          align-items: center;
          gap: 15px;

          .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 24px;
          }

          .stat-content {
            .stat-label {
              font-size: 14px;
              color: #666;
              margin-bottom: 5px;
            }

            .stat-value {
              font-size: 28px;
              font-weight: bold;
              color: #333;
            }
          }
        }
      }
    }

    .charts-row {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20px;
      margin-bottom: 20px;

      .chart-card {
        .chart {
          height: 300px;
        }
      }
    }

    .table-card {
      margin-bottom: 20px;
    }
  }

  @media (max-width: 1200px) {
    .overview-cards {
      grid-template-columns: repeat(2, 1fr) !important;
    }
    .charts-row {
      grid-template-columns: 1fr !important;
    }
  }

  @media (max-width: 768px) {
    .overview-cards {
      grid-template-columns: 1fr !important;
    }
  }
</style>
